package com.dhcc.sdc.cdss.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhcc.cdc.busi.dao.CdcOrdmastMapper;
import com.dhcc.cdc.busi.entity.CdcDictionaryEntity;
import com.dhcc.cdc.busi.entity.CdcOrdmastEntity;
import com.dhcc.cdc.sys.service.IDictionaryService;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.modules.system.entity.User;
import com.dhcc.sdc.busi.dao.SdcShowPremiseMapper;
import com.dhcc.sdc.busi.entity.SdcShowPremiseEntity;
import com.dhcc.sdc.cdss.dao.SdcCdssItemLogMapper;
import com.dhcc.sdc.cdss.dto.CdssEvalDto;
import com.dhcc.sdc.cdss.dto.CdssLabAndExamDto;

import com.dhcc.sdc.cdss.entity.SdcCdssItemLogEntity;
import com.dhcc.sdc.cdss.entity.SdcCdssItemMatchEntity;
import com.dhcc.sds.standard.dto.CdcOrdmastDto;
import com.dhcc.sds.standard.entity.SdsStandSourceEntity;
import com.dhcc.sds.standard.entity.SdsStandSourceFieldEntity;
import com.dhcc.sds.standard.service.ISdsStandSourceFieldService;
import com.dhcc.sds.standard.service.ISdsStandSourceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.sdc.cdss.dao.SdcCdssItemMapper;
import com.dhcc.sdc.cdss.service.ISdcCdssItemService;
import com.dhcc.sdc.cdss.entity.SdcCdssItemEntity;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * CDSS推荐方案项目表数据服务层接口
 * 
 * @ClassName: SdcCdssItemServiceImpl
 * @Description: TODO
 * @author sunyingjie
 * @date 2023-01-03 14:23:49
 */
@Service("sdcCdssItemService")
public class SdcCdssItemServiceImpl extends BaseServiceImpl<SdcCdssItemMapper, SdcCdssItemEntity> implements ISdcCdssItemService {

	@Resource
	private SdcShowPremiseMapper sdcShowPremiseMapper;
	@Autowired
	private ISdsStandSourceService standSourceService;
	@Autowired
	private ISdsStandSourceFieldService sdsStandSourceFieldService;
	@Resource
	private SdcCdssItemLogMapper sdcCdssItemLogMapper;


	@Override
	public List<SdcCdssItemEntity> page(Page<SdcCdssItemEntity> page, Map<String, Object> map) {
		return this.baseMapper.page(page, map);
	}
	@Override
	public List<SdcCdssItemEntity> list(Map<String, Object> map) {
		return this.baseMapper.list(map);
	}

	@Override
	public List<String>  handleJsonArrayData(JSONObject jsonObject, Long qcEntityId) {
		List<String> cdssNodeIds = new ArrayList<>();
		for (String key : jsonObject.keySet()){
			JSONArray jsonArray = jsonObject.getJSONArray(key);
			List<SdcCdssItemEntity> cdssItemEntities = new ArrayList<>();
			Integer itemType = 0;
			switch (key){
				case "推荐护理处置":
					cdssItemEntities = JSONObject.parseArray(jsonArray.toJSONString(), SdcCdssItemEntity.class);
					itemType = 5;
					handleCommonCdssItem(cdssItemEntities, qcEntityId, itemType, cdssNodeIds);
					break;
				case "推荐检验检查":
					List<CdssLabAndExamDto> cdssLabAndExamEntities = JSONObject.parseArray(jsonArray.toJSONString(), CdssLabAndExamDto.class);
					for (CdssLabAndExamDto cdssLabAndExamDto : cdssLabAndExamEntities){
						String LabAndExamType = cdssLabAndExamDto.getItemType();
						if (Objects.equals("126", LabAndExamType)){
							//检验
							itemType = 3;
						}else if (Objects.equals("122", LabAndExamType)){
							//检查
							itemType = 2;
						}
						SdcCdssItemEntity sdcCdssItemEntityNew = new SdcCdssItemEntity();
						BeanUtils.copyProperties(cdssLabAndExamDto, sdcCdssItemEntityNew);
						handleDetailsCdssItem(sdcCdssItemEntityNew, qcEntityId, itemType, cdssNodeIds);
					}
					break;
				case "推荐治疗方案":
					cdssItemEntities = JSONObject.parseArray(jsonArray.toJSONString(), SdcCdssItemEntity.class);
					itemType = 4;
					handleCommonCdssItem(cdssItemEntities, qcEntityId, itemType, cdssNodeIds);
					break;
				case "推荐评估量表":
					itemType = 1;
					List<CdssEvalDto> cdssEvalEntities = JSONObject.parseArray(jsonArray.toJSONString(), CdssEvalDto.class);
					for (CdssEvalDto cdssEvalDto : cdssEvalEntities){
						SdcCdssItemEntity sdcCdssItemEntityNew = new SdcCdssItemEntity();
						BeanUtils.copyProperties(cdssEvalDto, sdcCdssItemEntityNew);
						handleDetailsCdssItem(sdcCdssItemEntityNew, qcEntityId, itemType, cdssNodeIds);
					}
					break;
				case "鉴别诊断":
					break;

			}

		}
		return cdssNodeIds;
	}

	@Override
	public List<String> selectNodeIds(Long entityId) {
		return this.baseMapper.selectNodeIds(entityId);
	}

	@Override
	public void deleteByNodeIds(List<String> nodeIds) {
		this.baseMapper.deleteByNodeIds(nodeIds);
	}

	@Override
	public List<SdcShowPremiseEntity> selectByShowPremise(Map<String, Object> params) {
		List<SdcShowPremiseEntity> res = new ArrayList<>();
		String compare = (String) params.get("compare");
		String showPremise = "";
		if (!StringUtils.isEmpty(params.get("showPremise"))){
			try {
				showPremise = java.net.URLDecoder.decode((String) params.get("showPremise"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			List<String> list = handleRuleExpressions(showPremise);
			if (Objects.equals("all", compare)){
				String s = list.get(0);
				String[] split = s.split("_");
				params.put("expCode", split[0]);
				res = sdcShowPremiseMapper.list(params);
			}else {
				res = sdcShowPremiseMapper.selectByExpressions(list);
			}
		}

		for (SdcShowPremiseEntity sdcShowPremiseEntity : res){
			String ruleCal = "";
			if (!StringUtils.isEmpty(sdcShowPremiseEntity.getDataSource1()) && !StringUtils.isEmpty(sdcShowPremiseEntity.getDataSourceItem1())){
				SdsStandSourceEntity sourceEntity1 = standSourceService.selectById(sdcShowPremiseEntity.getDataSource1());
				SdsStandSourceFieldEntity sourceFieldEntity1 = sdsStandSourceFieldService.selectById(sdcShowPremiseEntity.getDataSourceItem1());
				ruleCal = sourceEntity1.getSourceDesc() + ":" + sourceFieldEntity1.getFieldDesc();
			}
			if (!StringUtils.isEmpty(sdcShowPremiseEntity.getParam1())){
				ruleCal = ruleCal + "(" + sdcShowPremiseEntity.getParam1() + ")";
			}
			if (!StringUtils.isEmpty(sdcShowPremiseEntity.getOperator1())){
				ruleCal = ruleCal + sdcShowPremiseEntity.getOperator1();
			}
			if (!StringUtils.isEmpty(sdcShowPremiseEntity.getDataSource2()) && !StringUtils.isEmpty(sdcShowPremiseEntity.getDataSourceItem2())){
				SdsStandSourceEntity sourceEntity2 = standSourceService.selectById(sdcShowPremiseEntity.getDataSource2());
				SdsStandSourceFieldEntity sourceFieldEntity2 = sdsStandSourceFieldService.selectById(sdcShowPremiseEntity.getDataSourceItem2());
				ruleCal = ruleCal + sourceEntity2.getSourceDesc() + ":" + sourceFieldEntity2.getFieldDesc();
			}
			if (!StringUtils.isEmpty(sdcShowPremiseEntity.getParam2())){
				ruleCal = ruleCal + "(" + sdcShowPremiseEntity.getParam2() + ")";
			}
			if (!StringUtils.isEmpty(sdcShowPremiseEntity.getOperator2())){
				ruleCal = ruleCal + sdcShowPremiseEntity.getOperator2();
			}
			sdcShowPremiseEntity.setRuleCal(ruleCal);
		}

		return res;
	}

	private void handleCommonCdssItem(List<SdcCdssItemEntity> cdssItemEntities, Long qcEntityId, Integer itemType, List<String> cdssNodeIds){
		for (SdcCdssItemEntity sdcCdssItemEntity : cdssItemEntities){
			handleDetailsCdssItem(sdcCdssItemEntity, qcEntityId, itemType, cdssNodeIds);
		}
	}


	private void handleDetailsCdssItem(SdcCdssItemEntity sdcCdssItemEntity, Long qcEntityId, Integer itemType, List<String> cdssNodeIds){
		SdcCdssItemEntity sdcCdssItemEntityNew = new SdcCdssItemEntity();
		sdcCdssItemEntityNew.setNodeId(sdcCdssItemEntity.getNodeId());
		sdcCdssItemEntityNew.setItemId(sdcCdssItemEntity.getItemId());
		sdcCdssItemEntityNew.setQcentityId(qcEntityId);
		sdcCdssItemEntityNew.setItemType(itemType);
		cdssNodeIds.add(sdcCdssItemEntity.getNodeId());
		SdcCdssItemEntity sdcCdssItemEntity1 = this.baseMapper.selectOne(sdcCdssItemEntityNew);

		User user = ShiroKit.getUser();
		String userName = user.getLoginName();
		if (StringUtils.isEmpty(sdcCdssItemEntity1)){
			//insert
			sdcCdssItemEntity.setQcentityId(qcEntityId);
			sdcCdssItemEntity.setIsCdss(1);
			sdcCdssItemEntity.setItemType(itemType);
			sdcCdssItemEntity.setTreatSource(sdcCdssItemEntity.getTreatSource());
			sdcCdssItemEntity.setRuleBasisHtml(sdcCdssItemEntity.getRuleBasisHtml());
			boolean isInsert = sdcCdssItemEntity.insert();
			if (isInsert){
				SdcCdssItemLogEntity sdcCdssItemLogEntityNew = new SdcCdssItemLogEntity();
				sdcCdssItemLogEntityNew.setEntityId(qcEntityId);
				sdcCdssItemLogEntityNew.setItemType(itemType);
				sdcCdssItemLogEntityNew.setOperType(1);
				sdcCdssItemLogEntityNew.setOperTime(new Date());
				sdcCdssItemLogEntityNew.setOperContent(sdcCdssItemEntity.getItemName());
				sdcCdssItemLogEntityNew.setOperUser(userName);
				sdcCdssItemLogEntityNew.insert();
			}
		}else {
			//update
			sdcCdssItemEntity1.setQcentityId(qcEntityId);
			sdcCdssItemEntity1.setItemDesc(sdcCdssItemEntity.getItemDesc());
			sdcCdssItemEntity1.setItemName(sdcCdssItemEntity.getItemName());
			sdcCdssItemEntity1.setSourceFlag(sdcCdssItemEntity.getSourceFlag());
			sdcCdssItemEntity1.setNoCondition(sdcCdssItemEntity.getNoCondition());
			sdcCdssItemEntity1.setCureId(sdcCdssItemEntity.getCureId());
			sdcCdssItemEntity1.setRuleBasisHtml(sdcCdssItemEntity.getRuleBasisHtml());
			sdcCdssItemEntity1.setTreatSource(sdcCdssItemEntity.getTreatSource());
			boolean isUpdate = sdcCdssItemEntity1.updateAllColumnById();
			if (isUpdate){
				SdcCdssItemLogEntity sdcCdssItemLogEntityNew = new SdcCdssItemLogEntity();
				sdcCdssItemLogEntityNew.setEntityId(qcEntityId);
				sdcCdssItemLogEntityNew.setItemType(itemType);
				sdcCdssItemLogEntityNew.setOperType(2);
				sdcCdssItemLogEntityNew.setOperContent(sdcCdssItemEntity.getItemName());
				sdcCdssItemLogEntityNew.setOperUser(userName);
				SdcCdssItemLogEntity sdcCdssItemLogEntity = sdcCdssItemLogMapper.selectOne(sdcCdssItemLogEntityNew);
				if (StringUtils.isEmpty(sdcCdssItemLogEntity)){
					sdcCdssItemLogEntityNew.setOperTime(new Date());
					sdcCdssItemLogEntityNew.insert();
				}else {
					sdcCdssItemLogEntity.setOperTime(new Date());
					sdcCdssItemLogEntity.updateAllColumnById();
				}


			}
		}
	}

	private List<String> handleRuleExpressions(String ruleExpressions) {
		//小括号及其里面内容
		String p1 = "\\(.*?\\)";
		List<String> res = new ArrayList<>();
		Pattern p = Pattern.compile(p1);
		Matcher m = p.matcher(ruleExpressions);
		while (m.find()){
			String ruleExpression = m.group().substring(1, m.group().length() - 1);
			res.add(ruleExpression);
		}
		return res;
	}

}